import React, { useReducer, useEffect, useState } from "react";
import queryApi from "../../api/query";
import { Alert } from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { deleteFileByS3 } from "../../utils/s3FileUpload";
const ComMaterialContext = React.createContext();

const dataReducer = (state, action) => {
  switch (action.type) {
    case "fetch_init":
      return action.payload;
    case "addComMaterial":
      return [...state, action.payload];
    case "editComMaterial":
      return state.map((item) => {
        return item._id === action.payload._id ? action.payload : item;
      });
    case "deleteComMaterial":
      return state.filter((material) => material._id !== action.payload);
    case "filterComMaterial":
      return action.payload;
    default:
      return state;
  }
};

export const ComMaterialProvider = ({ children }) => {
  const [ComMaterial, dispatch] = useReducer(dataReducer, []);
  const [isComMatLoading, setIsComMatLoading] = useState(false);
  const [isComMatError, setIsComMatError] = useState(false);
  const [companyMaterial, setCompanyMaterial] = useState([]);
  useEffect(() => {
    const fetchData = async () => {
      setIsComMatLoading(true);
      setIsComMatError(false);
      try {
        const token = await AsyncStorage.getItem("token");
        if (!token) {
          console.log("请求userId出错");
        }
        const result = await queryApi.get("/companymaterial/", {
          headers: { Authorization: token },
        });
        // console.log("企业内材料--", result.data.message);
        dispatch({ type: "fetch_init", payload: result.data.message });
        setCompanyMaterial(result.data.message);
      } catch (err) {
        console.log(err);
        setIsComMatError(true);
      }
      setIsComMatLoading(false);
    };
    fetchData();
  }, []);

  const addComMaterial = async (comMaterial, callback, Loading) => {
    try {
      const token = await AsyncStorage.getItem("token");
      if (!token) {
        console.log("请求userId出错");
      }
      const newComMaterial = await queryApi.post(
        "/companymaterial",
        comMaterial,
        {
          headers: { Authorization: token },
        }
      );

      dispatch({
        type: "addComMaterial",
        payload: newComMaterial.data.message,
      });
      let arr = [...companyMaterial, newComMaterial.data.message];
      setCompanyMaterial(arr);
      Loading();
      Alert.alert("", "添加材料成功", [
        {
          text: "确定",
          onPress: () => callback(),
        },
      ]);
      console.log("添加公司材料成功");
    } catch (err) {
      Loading();
      Alert.alert("", "添加材料失败");
      console.log("添加公司材料出错", err);
    }
  };

  const editComMaterial = async (comMaterial, Loading, regetGoods) => {
    try {
      const newComMaterial = await queryApi.patch(
        "/companymaterial/" + comMaterial._id,
        comMaterial
      );
      await regetGoods(); //重新获取商品
      dispatch({
        type: "editComMaterial",
        payload: newComMaterial.data.message,
      });
      let arr = companyMaterial.map((item) => {
        return item._id === newComMaterial.data.message._id
          ? newComMaterial.data.message
          : item;
      });
      setCompanyMaterial(arr);
      Loading();
      Alert.alert("", "修改材料成功");
    } catch (err) {
      Loading();
      Alert.alert("", "修改材料失败");
      console.log("修改公司材料出错", err);
    }
  };

  const deleteComMaterial = async (comId, Loading, regetGoods) => {
    try {
      const result = await queryApi.delete("/companymaterial/" + comId);
      const deletedGoods = result.data.message;
      // console.log("----", deletedGoods);
      await regetGoods(); //重新获取商品
      if (deletedGoods.length !== 0) {
        const imageKey = [];
        deletedGoods.forEach((item) => {
          item.image.forEach((i) => imageKey.push(i));
        });
        // console.log("----imageKey", imageKey);
        await deleteFileByS3(imageKey);
      }

      Loading(); //同理
      dispatch({ type: "deleteComMaterial", payload: comId });
      let arr = companyMaterial.filter((material) => material._id !== comId);

      setCompanyMaterial(arr);
      Alert.alert("", "删除材料成功");
    } catch (err) {
      Loading();
      Alert.alert("", "删除材料失败");
      console.log("删除公司材料出错", err);
    }
  };

  const filterComMaterial = (result, materialFilter) => {
    let list = companyMaterial;
    // console.log("context里面的---", companyMaterial);
    if (materialFilter.length !== 0) {
      if (materialFilter[0] === -1) {
        list = companyMaterial;
      } else if (materialFilter[1] === -1) {
        list = companyMaterial.filter(
          (item) => item.category === result[materialFilter[0]].category
        );
      } else {
        list = companyMaterial.filter(
          (item) =>
            item.category === result[materialFilter[0]].category &&
            item.type === result[materialFilter[0]].types[materialFilter[1]]
        );
      }
    }
    // console.log("list---", list);
    dispatch({ type: "filterComMaterial", payload: list });
  };

  const resetComMaterial = () => {
    dispatch({ type: "filterComMaterial", payload: companyMaterial });
  };

  return (
    <ComMaterialContext.Provider
      value={{
        comMaterial: ComMaterial,
        addComMaterial,
        editComMaterial,
        deleteComMaterial,
        filterComMaterial,
        isComMatError,
        isComMatLoading,
        companyMaterial,
        resetComMaterial,
      }}
    >
      {children}
    </ComMaterialContext.Provider>
  );
};

export default ComMaterialContext;
